<template>
  <div>
    <el-form>
      <el-row>
        <el-col :span="4">
            <el-form-item label="">
              <span style="margin-left: 10px;font-size:12px;color:#606266;"><b>标题</b></span>
              <el-input style="width:180px;margin-left:10px;" v-model="seachForm.a" placeholder="请输入课程标题" :maxlength="20" show-word-limit >
              </el-input>
            </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="">
            <span style="margin-left: 10px;font-size:12px;color:#606266;"><b>教师</b></span>
            <el-input style="width:180px;margin-left:10px" v-model="seachForm.b" placeholder="请输入教师姓名" :maxlength="20" show-word-limit >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="">
            <span style="margin-left: 10px;font-size:12px;color:#606266;"><b>课程状态</b></span>
            <el-select style="width: 140px;margin-left:10px" v-model="seachForm.c" placeholder="请选择课程状态">
                <el-option v-for="item in statusData" :key="item.c" :label="item.statusName" :value="item.id">                   
                </el-option>
              </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
        <el-button style="width:70px" type="primary" size="mini" @click="selectTeacher">搜索</el-button>
        <el-button style="width:70px;margin-left:10px" size="mini" plain @click="seachForm={}">重置</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col :span="4">
          <el-button @click="openAdd()" type="primary" plain style="margin-left:10px">添加课程</el-button>
      </el-col>
    </el-row>
    <div style="background:#fff;width:100%;height:100%;margin-top:10px">
      <!-- 全查 -->
      <el-table :data="tableData" style="width: 100%; margin-top: 10px; margin-left: 15px"  @selection-change="handleSelectionChange" :header-cell-class-name="'headerBg'">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="courseTitle" label="课程标题" align="center"  show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="teacherName" label="教师姓名" align="center">
        </el-table-column>
        <el-table-column prop="courseInfo" label="课程介绍" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="courseStatus" label="付费类型" align="center">
        <template slot-scope="scope">
            <span v-if="scope.row.payType == 0" color="#19caad;">免费</span>
            <span v-if="scope.row.payType == 1">付费</span>
          </template>
        </el-table-column>
        <el-table-column prop="courseStatus" label="课程状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.courseStatus"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="0"
              inactive-value="1" @change="upSwitch(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350px" align="center">
          <template slot-scope="scope">
          <el-button type="primary" size="small" style="background:none;border:0px"><span style="color:#409EFF;" @click="openXiangxi(scope.row)"><i class="el-icon-share"></i>详情</span>
          
          </el-button>
          <el-button type="primary" size="small" style="background:none;border:0px"><span style="color:#409EFF;" @click="openXiugai(scope.row)"><i class="el-icon-edit"></i>修改</span></el-button>
          <el-popconfirm class="ml-5" confirm-button-text='确定' cancel-button-text='我再想想' icon="el-icon-info" icon-color="red" title="您确定删除吗？" @confirm="delCourse(scope.row.id)">
              <el-button type="primary" size="small" slot="reference" style="background:none;border:0px"><span style="color:#409EFF;"><i class="el-icon-delete"></i>删除</span></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination :page-sizes="[5, 10, 15, 20]" :page-size="pages.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pages.total" background :current-page.sync="pages.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
    </div>
    <el-dialog :visible.sync="addButton" width="29%" style="text-align: left" :before-close="handleClose">
        <div slot="title" class="header-title" style="">
          课程信息
        </div>
        <el-form stripe style="width: 100%; text-align: left" :model="addForm" ref="addForm" :rules="rules" >
          <el-form-item>
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">课程封面</span>
            <el-upload class="avatar-uploader" action="" style="margin-top: -40px; margin-left: 100px" list-type="picture-card" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img height="148" v-if="teacherImg" :src="teacherImg" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item width="400px" prop="courseTitle">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">课程标题</span>
            <el-input style="width: 400px; margin-left: 20px" v-model="addForm.courseTitle" placeholder="请输入课程标题" :maxlength="20" show-word-limit clearable ></el-input>
          </el-form-item>
          <el-form-item width="400px" prop="courseInfo">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">课程介绍</span>
            <el-input style="width: 400px; margin-left: 20px" v-model="addForm.courseInfo" type="textarea" placeholder="请输入课程介绍" :maxlength="200" show-word-limit clearable></el-input>
          </el-form-item>
          <el-form-item width="400px" prop="subjectId">
            <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
            <span style="margin-left: 20px">课程科目</span>
            <el-cascader
              style="width: 148px; margin-left: 20px"
              v-model="addForm.subjectId"
              :options="dictData"
              placeholder="请选择课程科目"
              :props="{ label: 'dictName', value: 'id', children: 'children' }"
              filterable
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item  width="400px" prop="payType"> 
              <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
              <span style="margin-left: 20px; padding-right: 20px">付费类型</span>
              <template>
                <el-radio v-model="addForm.payType" :label="0">免费</el-radio>
                <el-radio v-model="addForm.payType" :label="1">付费</el-radio>
              </template>
          </el-form-item>
          <el-form-item  width="400px" v-if="addForm.payType=='1'">
              <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
              <span style="margin-left: 20px; padding-right: 20px">价　　钱</span>
              <el-input-number v-model="addForm.coursePrice" wplaceholder="请输入价格"></el-input-number>
          </el-form-item>

        </el-form>
          <div style="height:10px;margin-right: 20px;">
            <div style="float:right;">
              <el-button style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)" @click="addCourse()">确 定</el-button>
              <el-button @click="addButton = false" style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)">取 消</el-button>
            </div>  
          </div>
           
      </el-dialog>
  </div>
</template>

<script>

export default {

  components: {},
  data () {
    return {
      // 状态
      statusData:[
        {id:0,statusName:'已上架'},
        {id:1,statusName:'未上架'}
      ], 
      // 验证
        rules: {
        courseTitle: [{
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        }],
        courseInfo: [{
          required: true,
          message: '请输入课程介绍',
          trigger: 'blur'
        }],
        subjectId: [{
          required: true,
          message: '请选择科目',
          trigger: 'blur'
        }],
        payType: [{
          required: true,
          message: '请选择支付类型',
          trigger: 'blur'
        }],
        coursePrice: [
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          // 如果 coursePrice 为空，则设置其值为零
          this.coursePrice = 0;
        } else {
          // 如果 coursePrice 不为空，则验证其值是否为数字
          const reg = /^\d+(\.\d+)?$/;
          if (!reg.test(value)) {
            callback(new Error('课程价格必须为数字'));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur'
    }
  ]
      },
        // 查询表单
        seachForm:{},
        //课程表格
      tableData: [],
      // 菜单表格
      dictData:[],
      //教师表格
      teacherData:[],
      aa: '',
      ids: [],
      // 图片回显
      teacherImg:'',
      //添加时赋值
      imgTeacher:'',
      pages: {
        // 当前页
        pageNum: 1,
        // 每页几条数据
        pageSize: 5
      },
      addForm:{
        courseTitle:'',
        courseInfo:'',
        payType:'',
        subjectId:''
      },
      upForm:{},
      addButton:false,
      upButton:false,
      isEmpty:false,
      isValidInput:true,
      teacherId:0,
      teacherRole:'',
      id:0
    }
  },
  mounted () {
    this.id=JSON.parse(localStorage.getItem("user")).id
    this.teacherRole=JSON.parse(localStorage.getItem("user")).role
    if(this.teacherRole == 'ROLE_TEACHER'){this.$axios
        .get("/back_course/selectTeacherId", {
          params: {
            userId:this.id
          },
        })
        .then((res) => {
          if ((res.data.flag)) {
            //教师信息表格赋值
          this.teacherId=res.data.data.id
         
          
          }
        })
        .catch((err) => {});}
    
    this.selectTeacher()
    
  },
  computed: {},
  watch: {},
  created() {},
  methods: {
    //修改状态
    upSwitch(row){
      this.$axios.get("/back_course/upSwitch",{
          params: {
            id:row.id,
            courseStatus:row.courseStatus
            }})
          .then((res) => {
            if((res.data.code==200)){
              this.selectTeacher()
              if(row.courseStatus==0){
                this.$message.success("已上架")
              }
              if(row.courseStatus==1){
                this.$message.success("已下架")
              }
            }
          })
    },
    // 删除课程
    delCourse(id){
        this.$axios.get("/back_course/delCourse", {
          params: {
            id:id
          },
        })
        .then((res) => {
          if ((res.data.code == 200)) {
            this.selectTeacher()
            this.$message.success("删除成功!")
          }
        })
        .catch((err) => {});
    },
    // 打开修改
    openXiugai(row){
      this.selectTeacherById(row)
      this.teacherImg="http://101.43.223.224:8765/image/getImageById?id=" + row.courseImg
    
      this.seachTeacher()
      this.addButton=true
    },
    //关闭对话框
    handleClose(done) {
      // 在这里编写您的关闭逻辑
      // 例如执行某个操作后再关闭对话框
      this.addForm={}

      // 图片回显
      this.teacherImg= ""
      // 调用 done() 方法来关闭对话框
      this.addButton=false
    },
    openAdd(){
      this.addButton=true
      this.seachTeacher()
      this.addForm.payType=0
    },
    openXiangxi(row){
        // 跳转并传递参数
      this.$router.push({
        name: 'courseInfo',
        params: {
          id: row.id
        }
      });
    },
    // 查询树状结构 输出级联选择器
    selectTeacherById (row){
      this.$axios
        .get("/back_course/selectCourseByIdDict", {
          params: {
            id:row.id
          },
        })
        .then((res) => {
          if ((res.data.flag)) {
            //教师信息表格赋值
          this.addForm=res.data.data
          this.addForm.subjectId = res.data.data.subjectId.split(",").map(Number);     
          }
        })
        .catch((err) => {});
    },
    selectTeacher(){
      if(this.teacherRole == 'ROLE_TEACHER'){
        this.$axios
        .get("/back_course/teacherSelectCourse", {
          params: {
            pageNum: this.pages.pageNum,
            pageSize: this.pages.pageSize,
            courseTitle:this.seachForm.a,
            teacherName:this.seachForm.b,
            courseStatus:this.seachForm.c,
            id:this.id
          },
        })
        .then((res) => {
          if ((res.data.flag)) {
            //教师信息表格赋值
            this.tableData = res.data.data.content
            this.pages.total = res.data.data.totalSize
          }
        })
        .catch((err) => {});
      }
    if(this.teacherRole == 'ROLE_ADMIN'){
      this.$axios
        .get("/back_course/selectCourse", {
          params: {
            pageNum: this.pages.pageNum,
            pageSize: this.pages.pageSize,
            courseTitle:this.seachForm.a,
            teacherName:this.seachForm.b,
            courseStatus:this.seachForm.c
          },
        })
        .then((res) => {
          if ((res.data.flag)) {
            //教师信息表格赋值
            this.tableData = res.data.data.content
            this.pages.total = res.data.data.totalSize
          }
        })
        .catch((err) => {});
    }
        
    },
    // 查询课程数据
    seachTeacher() {
    this.$axios
      .get("/back_course/selectDict")
      .then((res) => {
        if (res.data.flag) {
          // 格式化课程科目数据
          this.dictData = this.formatDictData(res.data.data);
        }
      })
      .catch((err) => {
        console.error(err);
      });
  },
  // 将数据放入map中
  formatDictData(data) {
    return data.map((item) => this.formatDictItem(item));
  },
  // 对树状课程进行处理
  formatDictItem(item) {
    if (item.children && item.children.length > 0) {
      item.children = this.formatDictData(item.children);
    } else {
      // 最后一级的 children 设置为 null
      item.children = null; 
    }
    return item;
  },
    addCourse(){
      this.$refs['addForm'].validate(valid => {
        if (valid) {
          const formData = new FormData()
          // 课程图片
            if (this.imgTeacher) {
              formData.set('file1', this.imgTeacher, this.imgTeacher.name)
            }
          for (const key in this.addForm) {
            formData.set(key, this.addForm[key])
          }
          formData.set("teacherId", this.teacherId)
          formData.delete("upTime")
          if(this.addForm.payType==0){
            formData.set("coursePrice",0)
          }
          if(formData.has('id')){
            // 修改
            this.$axios.post("/back_course/updateCourse", formData).then((res) => {
              if (res.data.flag) {
                this.$message.success('修改成功')
                // 图片回显
                this.teacherImg=''
                //添加时赋值
                this.imgTeacher=''
                //清空表单
                this.addForm={}
                // 关闭窗口
                this.addButton = false 
                //刷新
                this.selectTeacher()
              } else {
                this.$message.error('warning', res.data.code)
              }
            }).catch((err) => {
              console.log(err)
            })
          }else{
            this.$axios.post("/back_course/addCourse", formData).then((res) => {
              if (res.data.flag) {
                this.$message.success('添加成功')
                // 图片回显
                this.teacherImg=''
                //添加时赋值
                this.imgTeacher=''
                //清空表单
                this.addForm={}
                // 关闭窗口
                this.addButton = false 
                //刷新
                this.selectTeacher()
              } else {
                this.$message.error('warning', res.data.code)
              }
            }).catch((err) => {
              console.log(err)
            })
          }     
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 图片格式验证
    beforeAvatarUpload(file){
      //上传图片格式
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 /1024 < 2
      if(!isJPG && !isPNG){
        this.$message.error('上传图片只能是JPG/PNG格式!')
        return false
      }
      if(!isLt2M){
        this.$message.error('上传图片大小不能超过2MB!')
        return false
      }
      //赋值
      this.imgTeacher=file
      this.teacherImg=URL.createObjectURL(file)
      //isJPG && isLt2M 自动提交 false 是点击确定后提交
      return false
    },
    handleSelectionChange (val) {
      this.ids = val.map((v) => v.id)
    },
    // 分页
    handleSizeChange (val) {
      this.pages.pageSize = val
      this.selectTeacher()
    },
    handleCurrentChange (val) {
      this.pages.pageNum = val
      this.selectTeacher()
    },
    handleAvatarSuccess() {

    },

  }
}
</script>
<style>
.headerBg{
  background: #f8f8f9 !important;
}
</style>
